<template>
  <div class="editor-wrapper">
    <div class="toolbar-wrapper">
      <div ref="toolbar" class="component-editor-tool-bar"></div>
    </div>
    <div class="title">
      <textarea ref="titleinput" @input="setTitleInputHeight" rows="1" v-model="article.articleTitle" placeholder="请输入文章标题..."></textarea>
    </div>
    <div class="content">
      <div class="component-editor" ref="editor"></div>
    </div>
    <div class="file-btn">
      <span @click="triggerFiles(true)">上传附件</span>
      <span @click="selectDingUsers">选择抄送</span>
      <br>
      <span @click="openModulechosen">{{currentModule? currentModule: '选择版块'}}<i class="el-icon-caret-bottom"></i></span>
      <span @click="openSectionchosen">{{currentSection? currentSection: '选择栏目'}}<i class="el-icon-caret-bottom"></i></span>
      <span @click="openProjectchosen">{{currentProject? currentProject: '选择课题'}}<i class="el-icon-caret-bottom"></i></span>
    </div>
    <div class="cover" v-if="showCover" @click="triggerFiles(false)"></div>
    <div class="file-wrapper" :style="{'bottom': showFiles? '0': '-300' + 'px'}">
      <div class="file-header">
        附件管理
        <span>添加</span>
        <input type="file" @change="uploadFile($event)">
      </div>
      <div class="file-list">
        <div class="file-item" v-for="(file, index) in article.articleAttachment" :key="file.id">
          <span class="file-name">{{file.name}}</span>
          <span v-if="!file.url" class="uploading">上传中...</span>
          <span v-if="file.url" class="del" @click="delFile(index)"><i class="el-icon-error"></i></span>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import sinaEmotions from '@/assets/emotion/sina'
import dingMixin from  '@/mixins/ding'
import formUtil from '@/utils/formUtil'

export default {
  data () {
    return {
      headers: {
        token: this.$cookie.get('token')
      },
      article: {
        sectionId: '',
        articleTitle: '',
        articleMasterId: '',
        articleMasterName: '',
        articleInfo: '',
        articleContent: '',
        articleFrom: 0,
        articleRange: 0,
        articleReaderid: '',
        articleStatus: '0',
        articleAttachment: [],
      },
      showFiles: false,
      showCover: false,
      formVerify: {
        articleTitle: '请输入标题',
        sectionId: '请选择版块和栏目'
      },
      currentModule: '',
      currentModuleId: '',
      currentSection: '',
      currentSectionId: '',
      currentProject: '',
      currentPeojectId: '',
      sections: [],
      modules: [],
      projects: [],
      timeName: '',
      editor: null,
      isModuleManager: false,
      isSectionManager: false,
      ccIds: [],
      ccNames: []
    }
  },
  mixins: [dingMixin],
  methods: {
    selectDingUsers() {
      this.complexPicker(20, [], this.ccIds).then(
        data => {
          this.ccIds = data.map(item => item.emplId);
          this.ccNames = data.map(item => item.name);
        }
      );
    },
    setTitleInputHeight() {
      this.$refs.titleinput.style.height = 'auto';
      this.$refs.titleinput.style.height = this.$refs.titleinput.scrollHeight + 'px'
    },
    openModulechosen() {
      let moduleCopy = formUtil.deepCopy(this.modules)
      moduleCopy.forEach((item) => {
        item.key = item.sectionName;
        item.value = item.id;
      })

      this.mobileChosen(moduleCopy, moduleCopy[0].key,(data) => {
        this.selectModule({id: data.value, sectionName: data.key})
      })
    },
    openSectionchosen() {
      let sectionsCopy = formUtil.deepCopy(this.sections)
      sectionsCopy.forEach((item) => {
        item.key = item.sectionName;
        item.value = item.id;
      })

      this.mobileChosen(sectionsCopy, sectionsCopy[0].key,(data) => {
        this.selectSection({id: data.value, sectionName: data.key})
      })
    },
    openProjectchosen() {
      let projectsCopy = formUtil.deepCopy(this.projects)
      projectsCopy.forEach((item) => {
        item.key = item.sectionName;
        item.value = item.id;
      })

      this.mobileChosen(projectsCopy, projectsCopy[0].key,(data) => {
        this.selectProject({id: data.value, sectionName: data.key})
      })
    },
    async uploadFile(e) {
      let file = e.target.files[0];
      if(file.size / 1024 / 1024 > 20) return this.mobileAlert('上传单个文件大小不能超过20MB!请压缩文件')
      var formData = new FormData();
      formData.append("file", file);
      formData.append("name", 'file');
      let newfile = {
        name: file.name,
        url: ''
      }
      this.article.articleAttachment.push(newfile)
      this.$httpN.upload('fileUpload', formData).then((res) => {
        if(res.status === 200 && res.data.code === 0) {
          this.mobileMessage('上传成功')
          newfile.url = res.data.url;
        }else{
          this.mobileAlert('上传文件出错,请重试')
        }
      })
    },
    delFile(idx){
      this.article.articleAttachment.splice(idx, 1)
    },
    triggerFiles(open) {
      if(open) {
        this.showCover = true;
        this.showFiles = true;
      }else{
        this.showFiles = false;
        setTimeout(() => {
          this.showCover = false;
        }, 300)
      }
    },
    async selectModule(e) {
      this.currentModule = e.sectionName;
      this.currentModuleId = e.id;
      this.article.articleDatatype = e.id;
      this.currentSection = '';
      this.currentSectionId = '';
      this.article.sectionId = '';
      this.sections = await this.$httpN.postQ('community/section/list', {'parentid': e.id});
      let isModuleManager = false;
      this.modules.forEach((moduleItem) => {
        if(moduleItem.id === e.id){
          let managerArr = moduleItem.sectionManageUserid.split(',');
          isModuleManager = managerArr.includes(this.userInfo.dingId);
        }
      })
      this.isModuleManager = isModuleManager;
      if(this.sections.length >0 ){
        this.sections = this.sections.filter((item) => {
          if(item.sectionPublisher !== '') {
            let managerArr = item.sectionManageUserid.split(',');
            let userArr = item.sectionPublisher.split(',');
            if(item.sectionRange === '0' || managerArr.includes(this.userInfo.dingId) || isModuleManager) {
              return true;
            }else {
              return userArr.includes(this.userInfo.dingId);
            }
          }else{
            return true;
          }
        })
      }
    },
    async selectSection(e) {
      this.currentSection = e.sectionName;
      this.currentSectionId = e.id;
      this.article.sectionId = e.id;
      this.currentProject = '';
      this.currentProjectId = '';
      this.projects = await this.$httpN.postQ('community/section/list', {'parentid': e.id});
      let isSectionManager = false;
      this.sections.forEach((moduleItem) => {
        if(moduleItem.id === e.id){
          let managerArr = moduleItem.sectionManageUserid.split(',');
          isSectionManager = managerArr.includes(this.userInfo.dingId);
        }
      })
      this.isSectionManager = isSectionManager;
      if(this.projects.length >0 ){
        this.projects = this.projects.filter((item) => {
          if(item.sectionPublisher !== '') {
            let managerArr = item.sectionManageUserid.split(',');
            let userArr = item.sectionPublisher.split(',');
            if(item.sectionRange === '0' || managerArr.includes(this.userInfo.dingId) || isSectionManager || isModuleManager) {
              return true;
            }else {
              return userArr.includes(this.userInfo.dingId);
            }
          }else{
            return true;
          }
        })
      }
    },
    async selectProject(e) {
      this.currentProject = e.sectionName;
      this.currentPeojectId = e.id;
      this.article.sectionId = e.id;
    },
    async save(status) {
      if(this.currentProject === '') return this.mobileMessage('请选择课题')
      this.article.articleAttachment.filter((file) => !!file.url);
      this.article.articleContent = this.editor.txt.html();
      this.article.articleInfo = this.editor.txt.text().replace(/&nbsp;/g, '');
      this.article.articleTitle = this.article.articleTitle.trim();
      if(!formUtil.verifyData(this.article, this.formVerify)) return;
      if(this.article.articleTitle.length > 30) return this.mobileMessage('标题长度不能超过30个字')
      this.article.articleStatus = status;
      if(this.ccIds.length > 0) {
        this.article.articleCcId = this.ccIds.join(',');
        this.article.articleCcName = this.ccNames.join(',');
      }
      if(this.articleId) {
        if(!await this.$httpN.postB('community/article/update', this.article)) return;
        this.mobileMessage('编辑成功');
        this.$router.go(-1);
        window.MOBILE_NEEDREFRESH = true;
      }else {
        if(!await this.$httpN.postB('community/article/save', this.article)) return;
        this.mobileMessage('创建成功');
        this.$router.go(-1);
        window.MOBILE_NEEDREFRESH = true;
      }
    }
  },
  async mounted() {
    this.mobileStopRefresh();
    this.articleId = this.$route.params.id;
    if(this.articleId) {
      let article = await this.$httpN.get('community/article/info/' + this.articleId);
      article.articleAttachment = JSON.parse(article.articleAttachment);
      article.articleAttachment.forEach((item) => item.isSuccess = true);
      this.article = article;
      this.sections = await this.$httpN.postQ('community/section/list', {'parentid': this.article.plateId});
      if(this.article.secondSectionId) {
        this.projects = await this.$httpN.postQ('community/section/list', {'parentid': this.article.firstSectionId});
        this.currentModule = this.article.plateName;
        this.currentSection = this.article.firstSectionName;
        this.currentProject = this.article.secondSectionName;
      }else{
        this.currentModule = this.article.plateName;
        this.currentSection = this.article.firstSectionName;
      }
      this.ccIds = article.articleCcId === '' ? []: article.articleCcId.split(',');
      this.ccNames = article.articleCcName === '' ? []: article.articleCcName.split(',');
    }else {
      this.article.articleMasterId = this.userInfo.dingId;
      this.article.articleMasterName = this.userInfo.realName;
    }
    this.modules = await this.$httpN.postQ('community/section/list', {'parentid': null})
    let E = window.wangEditor;
    if(this.$refs.toolbar) {
      var editor = new E(this.$refs.toolbar, this.$refs.editor)
      editor.customConfig.uploadImgServer = this.$http.adornUrl('/fileUpload');
      editor.customConfig.pasteIgnoreImg = true;
      editor.customConfig.uploadImgHeaders = {'token': this.$cookie.get('token')}
      editor.customConfig.uploadFileName = 'file'
      editor.customConfig.menus = ['head','bold','justify','emoticon','image']
      editor.customConfig.uploadImgHooks = {
        customInsert: function (insertImg, result, editor) {
          var url = result.url + '?x-oss-process=style/forbid'
          insertImg(url)
        }
      }
      editor.customConfig.emotions = [{title:'默认',type: 'image',content: sinaEmotions}]
      editor.create();
      this.editor = editor;
      if(this.articleId) editor.txt.html(this.article.articleContent);
    }

    this.mobileSetRightMenu([{id: 'caogao', text: '草稿'},{id: 'fabu', text: '发布'}], (directive) => {
      if(directive === 'caogao'){
        this.save(0)
      }else if(directive === 'fabu'){
        this.save(1)
      }
    });
  }
}
</script>

<style lang="scss" scoped>
  .editor-wrapper{
    height: 100vh;
    background: #FFF;
    padding: 0 12px;
    position: relative;
    overflow: hidden;
    .title{
      border-bottom: 1px solid #ccc;
      textarea{
        width: 100%;
        line-height: 30px;
        border: none;
        outline: none;
        font-size: 18px;
        color:#606266;
        font-weight: 500;
        overflow-y:hidden;
        max-height: 64px;
      }
    }
    .file-btn{
      line-height: 40px;
      span{
        background: #409EFF;
        color: white;
        padding: 5px 10px;
        border-radius: 5px;
      }
    }
    .content{
      height: calc(100% - 200px);
      padding-top: 10px;
      border-bottom: 1px solid #ccc;
    }
    .component-editor{
      height: 100%;
      width: 100%;
    }
    .toolbar-wrapper{
      padding: 10px 0;
      border-bottom: 1px solid #ccc;
    }
    .file-wrapper{
      position: absolute;
      bottom: -300px;
      left: 2%;
      width: 96%;
      height: 300px;
      background: #FFF;
      border-radius: 10px 10px 0 0 ;
      transition: .3s;
      z-index: 3;
      padding: 20px;
      .file-header{
        font-weight: bold;
        font-size: 16px;
        border-bottom: 1px solid black;
        padding-bottom: 10px;
        position: relative;
        span{
          position: absolute;
          top: 0;
          right: 0;
        }
        input{
          position: absolute;
          top: 0;
          right: 0;
          width: 32px;
          opacity: 0;
        }
      }
      .file-list{
        padding-top: 10px;
        max-height: 230px;
        overflow: scroll;
      }
      .file-item{
        line-height: 24px;
        position: relative;
        padding-right: 50px;
        margin-bottom: 10px;
        .del, .uploading{
          position: absolute;
          right:0;
          top:0;
          bottom: 0;
          margin: auto 0;
          text-align: center;
        }
        .uploading{
          color: red;
        }
      }
    }
    .cover{
      position:absolute;
      left:0px;
      top:0px;
      background:rgba(0, 0, 0, 0.4);
      width:100%;  /*宽度设置为100%，这样才能使隐藏背景层覆盖原页面*/
      height:100%;
      filter:alpha(opacity=60);  /*设置透明度为60%*/
      opacity:0.6;  /*非IE浏览器下设置透明度为60%*/
      z-Index:2;  
    }
  }
</style>